package binarytree

func rightSideView(root *TreeNode) []int {
	ans := []int{}
	if root == nil {
		return ans
	}

	queue := []*TreeNode{root}
	var node *TreeNode
	curLen := 1
	nextLen := 0

	for len(queue) != 0 {
		for curLen != 0 {
			node = queue[0]
			queue = queue[1:]
			if node.Left != nil {
				queue = append(queue, node.Left)
				nextLen++
			}
			if node.Right != nil {
				queue = append(queue, node.Right)
				nextLen++
			}
			curLen--
		}
		ans = append(ans, node.Val)
		curLen = nextLen
		nextLen = 0
	}

	return ans
}
